<template>
  <div>
    <input v-model="searchQuery" @input="debouncedSearch" placeholder="搜索知识库...">
    <div v-if="results.length" class="results">
      <div v-for="(item, index) in results" :key="index" class="result-item">
        <h3>{{ item.title }}</h3>
        <p>{{ item.content.slice(0, 150) }}...</p>
        <span class="score">相关度: {{ (item.score * 100).toFixed(1) }}%</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { debounce } from 'lodash-es'

const props = defineProps({
  knowledgeId: String,
  apiKey: String
})

const searchQuery = ref('')
const results = ref([])

const debouncedSearch = debounce(async () => {
  if (!searchQuery.value.trim()) {
    results.value = []
    return
  }

  const response = await fetch(`https://api.dify.ai/v1/knowledge/${props.knowledgeId}/search`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${props.apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: searchQuery.value,
      top_k: 5
    })
  })

  results.value = await response.json()
}, 500)
</script>